package com.nf;

import com.nf.handler.Constants;

import java.awt.*;
import java.beans.PropertyDescriptor;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Arrays;

public class MiniGerenourProcessor extends MiniBeanProcessor {

    public MiniGerenourProcessor() {
        super();
    }

    @Override
    public int[] mapColumnsToProperties(ResultSetMetaData metaData, PropertyDescriptor[] props) throws SQLException {
        int count = metaData.getColumnCount();

        int[] columnToProperty = new int[count + 1];

        Arrays.fill(columnToProperty, Constants.PROPERTY_NOT_FOUND);

        for (int i = 1; i <= count; i++) {
            String name=getColumnName(metaData,i);
            String camelCase=toCamelCase(name);

            String generousColumnName = name.replace("_", "");

            for (int j=1;j<props.length;j++){
                PropertyDescriptor descriptor = props[j];

                if (camelCase.equals(descriptor.getName())||generousColumnName.equals(descriptor.getName())){

                    columnToProperty[i]=j;

                    break;
                }


            }
        }
        return columnToProperty;
    }

    private String getColumnName(ResultSetMetaData metaData,int i) throws SQLException {
        String columnName=metaData.getColumnLabel(i);
        if (columnName==null||columnName.length()==0) {
            columnName=metaData.getColumnName(i);
        }
        return columnName;
    }

    public static String toCamelCase(String underlineStr){
        if (underlineStr == null) {
            return null;
        }
        //分成数组
        char[] charArray=underlineStr.toCharArray();
        //判断循环字符是否为"_"
        boolean underlineBefore = false;
        StringBuffer buffer=new StringBuffer();
        for (int i = 0; i < charArray.length; i++) {
            //判断当前字符是否是"_",如果是跳出循环
            if (charArray[i]==95)
            {
                underlineBefore=true;
            }else if(underlineBefore){
                //如果为true，代表上次的字符是"_",当前字符需要转换成大写
                buffer.append(charArray[i] -=32);
                underlineBefore=false;
            }else{
                //不是"_"后的字符就直接追加
                buffer.append(charArray[i]);
            }
        }
        return buffer.toString();
    }
}
